/*******************************************************************************
 * Copyright (c) 2013 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package com.niannian.util.network;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import android.util.Log;


import com.niannian.BaseActivity;
import com.niannian.MyApplication;
import com.niannian.util.FileUtils;
import com.niannian.util.MD5Util;
import com.niannian.util.VAR;

public class QHttpUtil {
	public interface DownloadProgress {
		void setCurrentDownloadBytes(int downloadBytes);
	}

	/**
	 * Return the MIME type based on the specified file name.
	 * 
	 * @param fileName
	 *            path of input file.
	 * @return MIME type.
	 */
	public static String getContentType(String fileName) {
		// return new MimetypesFileTypeMap().getContentType(fileName);
		return null;
	}

	/**
	 * Return the MIME type based on the specified file name.
	 * 
	 * @param file
	 *            File
	 * @return MIME type.
	 */
	public static String getContentType(File file) {
		// return new MimetypesFileTypeMap().getContentType(file);
		return null;
	}

	/**
	 * Return the list of query parameters based on the specified query string.
	 * 
	 * @param queryString
	 * @return the list of query parameters.
	 */
	public static List<QParameter> getQueryParameters(String queryString) {
		if (queryString.startsWith("?")) {
			queryString = queryString.substring(1);
		}

		List<QParameter> result = new ArrayList<QParameter>();

		if (queryString != null && !queryString.equals("")) {
			String[] p = queryString.split("&");
			for (String s : p) {
				if (s != null && !s.equals("")) {
					if (s.indexOf('=') > -1) {
						String[] temp = s.split("=");
						if (temp.length == 2) {
							result.add(new QParameter(temp[0], temp[1]));
						}
					}
				}
			}
		}

		return result;
	}

	/**
	 * Convert %XX
	 * 
	 * @param value
	 * @return
	 */
	public static String formParamDecode(String value) {
		int nCount = 0;
		for (int i = 0; i < value.length(); i++) {
			if (value.charAt(i) == '%') {
				i += 2;
			}
			nCount++;
		}

		byte[] sb = new byte[nCount];

		for (int i = 0, index = 0; i < value.length(); i++) {
			if (value.charAt(i) != '%') {
				sb[index++] = (byte) value.charAt(i);
			} else {
				StringBuilder sChar = new StringBuilder();
				sChar.append(value.charAt(i + 1));
				sChar.append(value.charAt(i + 2));
				sb[index++] = Integer.valueOf(sChar.toString(), 16).byteValue();
				i += 2;
			}
		}
		String decode = "";
		try {
			decode = new String(sb, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return decode;
	}

	public static boolean isEmpty(String str) {
		if (null == str || str.equals("")) {
			return true;
		} else {
			return false;
		}
	}

	public static Map<String, String> splitResponse(String response) {
		Map<String, String> map = new HashMap<String, String>();
		if (!QHttpUtil.isEmpty(response)) {
			String[] array = response.split("&");
			if (array.length > 2) {
				String tokenStr = array[0]; // oauth_token=xxxxx
				String secretStr = array[1];// oauth_token_secret=xxxxxxx
				String[] token = tokenStr.split("=");
				if (token.length == 2) {
					map.put("oauth_token", token[1]);
				}
				String[] secret = secretStr.split("=");
				if (secret.length == 2) {
					map.put("oauth_token_secret", secret[1]);
				}
			}
		}
		return map;
	}

	public static File download(String url, String savePath, DownloadProgress downloadProgress) {
		File downloadfile = new File(savePath);
		try {

			if (downloadfile.exists())
				return downloadfile;

			System.gc();
			System.runFinalization();

			HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
			con.setRequestMethod("GET");
			con.setRequestProperty("Accept-Encoding", "gzip, identity");
			con.setDoInput(true);
			con.connect();
			String encode = con.getContentEncoding();

			File cachefilenametmp = new File(savePath + ".tmp");
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(cachefilenametmp));
			byte[] buf = new byte[1024];
			int count = 0, len = 0;

			InputStream in = con.getInputStream();

			if ((encode != null) && encode.equals("gzip")) {
				GZIPInputStream zipin = new GZIPInputStream(in);
				if (zipin != null) {
					while ((len = zipin.read(buf)) > 0) {
						bos.write(buf, 0, len);
						count += len;
						downloadProgress.setCurrentDownloadBytes(count);
					}
					bos.close();
					zipin.close();
					in.close();
					cachefilenametmp.renameTo(downloadfile);
					return downloadfile;
				}
			}

			while ((len = in.read(buf)) > 0) {
				bos.write(buf, 0, len);
				count += len;
				downloadProgress.setCurrentDownloadBytes(count);
			}
			bos.close();
			in.close();
			cachefilenametmp.renameTo(downloadfile);
			return downloadfile;
		} catch (Exception localException) {
		}
		return null;
	}

	public static byte[] download_image1(String stringurl) {
		try {
			System.gc();
			System.runFinalization();

			String cachefilename = MyApplication.FILE_PATH_TEMP + MD5Util.encode(stringurl)
					+ FileUtils.getImageFileExtension(stringurl);
			File cachefile = new File(cachefilename);
			Log.i("download_image1", cachefilename);
			if (cachefile.exists()) {
				Log.i("download_image1", "exists: " + cachefilename);
				return FileUtils.getBytes(cachefile);
			}
			HttpURLConnection con = (HttpURLConnection) new URL(stringurl).openConnection();
			con.setRequestMethod("GET");
			con.setRequestProperty("Accept-Encoding", "gzip, identity");
			con.setDoInput(true);
			con.connect();
			String encode = con.getContentEncoding();

			File cachefilenametmp = new File(cachefilename + ".tmp");
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(cachefilenametmp));
			byte[] buf = new byte[1024];
			int count = 0, len = 0;
			int contentlen = con.getContentLength();

			Log.i(VAR.LEVEL_INFO, stringurl + "[download1 size:" + contentlen + "Content-Encode" + encode + "]");

			InputStream in = con.getInputStream();

			if ((encode != null) && encode.equals("gzip")) {
				GZIPInputStream zipin = new GZIPInputStream(in);
				if (zipin != null) {
					while ((len = zipin.read(buf)) > 0) {
						bos.write(buf, 0, len);
						baos.write(buf, 0, len);
						count += len;
					}
					baos.close();
					bos.close();
					zipin.close();
					in.close();
					cachefilenametmp.renameTo(cachefile);
					return baos.toByteArray();
				}
			}

			while ((len = in.read(buf)) > 0) {
				bos.write(buf, 0, len);
				baos.write(buf, 0, len);
				count += len;
			}
			baos.close();
			bos.close();
			in.close();
			cachefilenametmp.renameTo(cachefile);
			return baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
